package com.hss01248.facedetect.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.ImageFormat;
import android.graphics.Point;
import android.graphics.PointF;
import android.hardware.Camera;
import android.hardware.Camera.PreviewCallback;
import android.media.ExifInterface;
import android.media.FaceDetector;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.speech.tts.TextToSpeech;

import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.faceplusplus.api.FaceDetecter;
import com.facepp.error.FaceppParseException;
import com.facepp.http.HttpRequests;
import com.facepp.http.PostParameters;
import com.google.gson.Gson;
import com.hss01248.facedetect.BaseURL;
import com.hss01248.facedetect.CheckType;
import com.hss01248.facedetect.FaceCj;
import com.hss01248.facedetect.MyBitmapUtils;
import com.hss01248.facedetect.MyImageFileUtils;
import com.hss01248.facedetect.R;
import com.hss01248.facedetect.ShootListener;
import com.hss01248.facedetect.constant.Global;
import com.hss01248.facedetect.response.CheckTicketResponse;
import com.hss01248.facedetect.response.CollectionFaceSaleTicketResponse;
import com.hss01248.facedetect.response.FaceDataCollectionResponse;
import com.hss01248.facedetect.response.FaceDataComparisonForOneResponse;
import com.hss01248.facedetect.response.FaceDataComparisonResponse;
import com.hss01248.facedetect.utils.Base64Utils;
import com.hss01248.facedetect.utils.DialogUtils;
import com.hss01248.facedetect.utils.MyProgressUtils;
import com.hss01248.facedetect.utils.SHExtends;
import com.hss01248.facedetect.utils.SPUtils;
import com.hss01248.facedetect.utils.ToastUtil;
import com.hss01248.facedetect.utils.httpUtils;
import com.hss01248.facedetect.view.FaceMask;
import com.hss01248.facedetect.view.LoadingView;
import com.hss01248.titlebarlib.Titlebar;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;


public class CollectActivity extends BaseActivity implements Callback, PreviewCallback, ShootListener {


    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CheckType.handler_collect_qrCode:
                    String typeData = (String) msg.obj;
//                    faceDataCollection(CheckType.TYPE_QRCODE,typeData,"");

                    break;
                case CheckType.handler_collect_IDCard:

                    break;
            }
        }
    };
    private TextView tv_message;

    /**********************语音合成**********************/
//语音引擎
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            } else {
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    private static final String TAG = "PhoneActivity";
    private TextToSpeech mSpeech = null;
    private static float m_voice_speed = 1.2f;   //合成语音的语速
    private static float m_voice_pitch = 1.0f;   //合成语音的语调
    /****************************************************/


    SurfaceView svPreview;
    FaceMask fmMask;
    LoadingView loadingView;
    RelativeLayout root;
    private Camera mCamera;
    private HandlerThread handleThread;
    private Handler detectHandler;
    private int width = 640;
    private int height = 480;
    private FaceDetecter facedetecter;

    Activity activity;
    Titlebar titlebar;
    private ImageView img_collect;
    private Button btn_reTake;
    private Button btn_confirm;

    Bitmap bitmap_collect;
    String filePath;
    int caseValue;
    String checkType;
    String typeData;
    String imgUrl;
    String rowKey;
    String barcodeNo;
    String task;
    String certificateTypeStr, humanCrednum, humanName;

    long exitTime_take = 0;
    long exitTime_confirm = 0;
    private SHExtends she;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_collect);

//        获取传来的值
        caseValue = getIntent().getIntExtra("caseValue", 0);
        checkType = getIntent().getStringExtra("checkType");
        typeData = getIntent().getStringExtra("typeData");
        imgUrl = getIntent().getStringExtra("imgUrl");
        rowKey = getIntent().getStringExtra("rowKey");
        barcodeNo = getIntent().getStringExtra("barcodeNo");
        task = getIntent().getStringExtra("task");
        certificateTypeStr = getIntent().getStringExtra("certificateTypeStr");
        humanCrednum = getIntent().getStringExtra("humanCrednum");
        humanName = getIntent().getStringExtra("idName");

        svPreview = (SurfaceView) findViewById(R.id.sv_preview_track);
        fmMask = (FaceMask) findViewById(R.id.fm_mask_track);
        root = (RelativeLayout) findViewById(R.id.root);
        titlebar = (Titlebar) findViewById(R.id.titlebar);
        tv_message = (TextView) findViewById(R.id.ca_tv_message);


        titlebar.init(this);

        titlebar.getRootView().setBackgroundColor(Color.parseColor("#43aea8"));
        titlebar.getIvLeft().setVisibility(View.INVISIBLE);
        titlebar.getTvRight().setVisibility(View.INVISIBLE);
        activity = this;


        img_collect = (ImageView) findViewById(R.id.ca_img_collect);
        btn_reTake = (Button) findViewById(R.id.ca_btn_reTake);
        btn_confirm = (Button) findViewById(R.id.ca_btn_confirm);
        btn_reTake.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ((System.currentTimeMillis() - exitTime_take) > 2000) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            fmMask.setShoot();
                        }
                    });
                    exitTime_take = System.currentTimeMillis();
                } else {
                    ToastUtil.showToast("请2秒后再点击");
                }

            }
        });
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        final File file = new File(dir, "capture" + ".jpg");
        filePath = file.getAbsolutePath();

        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        if (caseValue == 100010) {
            titlebar.setTitle("人脸比对");
            btn_reTake.setText("请拍照");
            tv_message.setText("请进行人脸比对");
        } else {
            titlebar.setTitle("人脸采集");
        }


        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


//                if (checkType.equals(CheckType.TYPE_QRCODE)) {
//
//
//                }else {
//                }


                if ((System.currentTimeMillis() - exitTime_confirm) > 2000) {
                    work();
                    exitTime_confirm = System.currentTimeMillis();
                } else {

                    ToastUtil.showToast("请2秒后再点击");
                }

            }
        });

        try {
            initData();
        } catch (Exception e) {
            Toast.makeText(this, "异常" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }


        mSpeech = new TextToSpeech(CollectActivity.this, new TTSListener());

        initBote();

    }

    private void initBote() {

        try {
            she = new SHExtends("/dev/ttyS3", "9600");
            she.open();
        } catch (Exception e) {
            ToastUtil.showToast("灯带Com口异常：" + e.getMessage());
            e.printStackTrace();
        }
    }

    //播放合成语音
    public void PlayAudioFile(String str) {
        //设置中文
        int supported = mSpeech.setLanguage(Locale.CHINA);
        mSpeech.setSpeechRate(m_voice_speed);
        mSpeech.setPitch(m_voice_pitch);

        if ((supported != TextToSpeech.LANG_AVAILABLE) && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
            //语言设置失败
            Log.i(TAG, "中文设置失败");
        } else {
            Log.i(TAG, "中文设置成功");
        }
        //mSpeech.speak(str, TextToSpeech.QUEUE_FLUSH, null);
        mSpeech.speak(str, TextToSpeech.QUEUE_ADD, null);

    }

    private void initData() {
        handleThread = new HandlerThread("dt");
        handleThread.start();
        detectHandler = new Handler(handleThread.getLooper());
        svPreview.getHolder().addCallback(this);
        svPreview.setKeepScreenOn(true);
        facedetecter = new FaceDetecter();
        facedetecter.init(this, Global.FACEPP_KEY);
        facedetecter.setTrackingMode(true);
    }

    void work() {
//                逻辑判断说明:
//                是否是免费票票：task
//                然后检票采集；
        if (task == null) {

            if (caseValue == 100009) {

//                        三目运算符
//                        barcodeno为空，则二维码检票
//                        barcodeNo不为空，则为身份证检票
                faceDataCollection(checkType, barcodeNo == null ? typeData : barcodeNo, Base64Utils.imageToBase64Str(filePath));

            } else {
                // TODO: 2019/7/31
                //caseValue==100010 匹配的情况  ??
                faceDataComparisonForOne(checkType, Base64Utils.imageToBase64Str(filePath), imgUrl, barcodeNo == null ? typeData : barcodeNo, rowKey);

////                             二维码
//                        if (checkType.equals(CheckType.TYPE_QRCODE)) {
//
//                        } else {
////                            身份证
//
//                        }
            }
        } else {
            if (task.equals("free")) {
//                        免费票采集
                collectionFaceSaleTicket(Base64Utils.imageToBase64Str(filePath), "", "", "");

            } else if (task.equals("special")) {
//                         带证件免费票采集

                collectionFaceSaleTicket(Base64Utils.imageToBase64Str(filePath), humanCrednum == null ? "" : humanCrednum, certificateTypeStr == null ? "" : certificateTypeStr, humanName == null ? "" : humanName);
            }
        }


    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        try {
            //            特别注意，
            //            在手机上，前置是1，后置是0
            //            在工控机上，前置是0

            if (Camera.getNumberOfCameras() > 1) {
                mCamera = Camera.open(1);
            } else {
                mCamera = Camera.open(0);
            }
            img_collect = (ImageView) findViewById(R.id.ca_img_collect);
            fmMask.setCamera(mCamera, img_collect, (CollectActivity) activity, she);
            if (null == mCamera) {
                Toast.makeText(this, "摄像头为空", Toast.LENGTH_SHORT).show();
                return;
            }
            mCamera.setDisplayOrientation(90);
            Camera.Parameters para = mCamera.getParameters();

//            para.setPictureFormat(ImageFormat.JPEG);
//            para.setPictureSize(720, 1280);
//            // 设置JPG照片的质量
//            para.set("jpeg-quality", 100);


            Point showingArea = new Point();
            WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
            Display display = wm.getDefaultDisplay();
            int screenWidth = display.getWidth();
            int screenHeight = display.getHeight();

            int topHeight = dip2px(activity, 25 + 44);//状态栏+titlebar
            showingArea.set(screenWidth, screenHeight - topHeight);


            Point point = getBestCameraResolution(para, showingArea);

            width = point.x;
            height = point.y;
//            width=640;
//            height=480;
            width = 352;
            height = 288;

            Log.i("size", "size w:" + width + "--h:" + height);
        /*:1920--h:1080
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:1440--h:1080
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:1280--h:720
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:1056--h:864
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:960--h:720
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:720--h:480
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:640--h:480
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:352--h:288
09-19 15:30:11.068 19768-19768/com.hss01248.facedemo E/size: size w:320--h:240*/


            para.setPreviewSize(width, height);

            mCamera.setParameters(para);


        } catch (Exception e) {
            Toast.makeText(this, "异常" + e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }

    public static int dip2px(Context context, float dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private Point getBestCameraResolution(Camera.Parameters parameters, Point screenResolution) {
        float tmp = 0f;
        float mindiff = 100f;
        float x_d_y = (float) screenResolution.x / (float) screenResolution.y;
        Camera.Size best = null;
        List<Camera.Size> supportedPreviewSizes = parameters.getSupportedPreviewSizes();
        for (Camera.Size s : supportedPreviewSizes) {
            tmp = Math.abs(((float) s.height / (float) s.width) - x_d_y);
            if (tmp < mindiff) {
                mindiff = tmp;
                best = s;
            }
        }
        return new Point(best.width, best.height);
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        try {
            if (mCamera == null) return;
            mCamera.setPreviewDisplay(holder);
            mCamera.setDisplayOrientation(90);

            mCamera.startPreview();
            mCamera.setPreviewCallback(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mCamera == null) return;
        mCamera.setPreviewCallback(null);
        mCamera.stopPreview();
        mCamera.release();
        mCamera = null;
    }

    @Override
    public void onPreviewFrame(final byte[] data, final Camera camera) {
        camera.setPreviewCallback(null);
        if (mCamera == null) return;

        detectHandler.post(new Runnable() {
            @Override
            public void run() {
                int is = 0;
                final byte[] ori = new byte[width * height];
                for (int x = width - 1; x >= 0; x--) {
                    for (int y = height - 1; y >= 0; y--) {
                        ori[is++] = data[y * width + x];
                    }
                }

                final FaceDetecter.Face[] faceinfo = facedetecter.findFaces(ori, height, width);


                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        fmMask.setFaceInfo(faceinfo);
                    }
                });

                try {
                    camera.setPreviewCallback(CollectActivity.this);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        facedetecter.release(this);
        handleThread.quit();
        detectHandler = null;

        if (mSpeech != null) {
            mSpeech.shutdown();
        }
        if (she != null) {
            she.lightOff();
            she.close();
        }
    }


    @Override
    public void passShoot(Camera camera, ImageView img_collect, Activity activity, SHExtends fm_she) {

        try {
            takePic(camera, img_collect, activity, fm_she);
        } catch (Exception e) {

        }

    }

    private void takePic(Camera camera, final ImageView img_collect, Activity cactivity, SHExtends fm_she) {

        activity = cactivity;
        she = fm_she;

        if (camera != null) {
            Camera.Parameters param = camera.getParameters();
            param.setPictureSize(640, 480);//如果不设置会按照系统默认配置最低160x120分辨率，对应参数是对的

            camera.setParameters(param);

            camera.takePicture(null, null, null, new Camera.PictureCallback() {

                @Override
                public void onPictureTaken(byte[] data, Camera camera) {

                    //也会影响拍摄分辨率
//                    720*960
                    Bitmap bitmap = MyBitmapUtils.byteToBitmap(data, 640, 720);

                    //然后将bitmap旋转270度
                    final Bitmap bitmap1 = MyBitmapUtils.rotateBitmap(bitmap, 270, true);
                    bitmap.recycle();


                    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    final File file = new File(dir, "capture" + ".jpg");
                    filePath = file.getAbsolutePath();

                    if (!file.exists()) {
                        try {
                            file.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }

                    FileOutputStream outSteam = null;
                    try {
                        outSteam = new FileOutputStream(file);
                        bitmap1.compress(Bitmap.CompressFormat.JPEG, 100, outSteam);
                        bitmap1.recycle();

                        img_collect.post(new Runnable() {
                            @Override
                            public void run() {

                                bitmap_collect = FaceCj.cutFace(BitmapFactory.decodeFile(file.getAbsolutePath()), CollectActivity.this);
                                MyBitmapUtils.saveBitmap(bitmap_collect, file.getAbsoluteFile());
                                img_collect.setImageBitmap(bitmap_collect);

//                                findFace(facedetecter, BitmapFactory.decodeFile(file.getAbsolutePath()));

                            }
                        });


                    } catch (IOException e) {
                        e.printStackTrace();
                    } finally {

                        if (outSteam != null) {
                            try {
                                outSteam.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }


                    }
                    camera.startPreview();  //如果不调用 ，则画面不会更新

                }
            });
        }
    }

//    private Bitmap findFace(FaceDetecter facedetecter, Bitmap bitmap) {
//
//        FaceDetecter.Face[] facesInfos = facedetecter.findFaces(bitmap);
//
//        for (int i = 0; i < facesInfos.length; i++) {
//            Arrays.sort(new float[]{facesInfos[i].right - facesInfos[i].left});
//        }
//
//
//        face = facesInfos[facesInfos.length - 1];
//        myMidPoint = new PointF();
//        face.getMidPoint(myMidPoint);
//        myEyesDistance = face.eyesDistance();   //得到人脸中心点和眼间距离参数，并对每个人脸进行画框
//        wuchax = myEyesDistance / 2 + myEyesDistance;
//        wuchay = myEyesDistance * 2 / 3 + myEyesDistance;
//
//        if (myMidPoint.x - wuchax < 0) {//判断左边是否出界
//            tx = 0;
//        } else {
//            tx = (int) (myMidPoint.x - wuchax);
//        }
//        if (myMidPoint.x + wuchax > cwidth) {//判断右边是否出界
//            bx = cwidth;
//        } else {
//            bx = (int) (myMidPoint.x + wuchax);
//        }
//        if (myMidPoint.y - wuchay < 0) {//判断上边是否出界
//            ty = 0;
//        } else {
//            ty = (int) (myMidPoint.y - wuchay);
//        }
//        if (myMidPoint.y + wuchay > cheight) {//判断下边是否出界
//            by = cheight;
//        } else {
//            by = (int) (myMidPoint.y + wuchay);
//        }
//
//        try {
//            return Bitmap.createBitmap(bitmap, tx, ty, bx - tx, by - ty + 5);//这里可以自行调整裁剪宽高
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        bitmap.recycle();
//        return bitmap;
//
//
//    }

    void checkTicket(final String checkType, final String typeData, final String gateNo) {
        new Thread(new Runnable() {
            @Override
            public void run() {

                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {

                    param.put("searchDataType", checkType);
                    param.put("searchData", typeData);
                    param.put("checkCount", -1);
                    param.put("gateNo", gateNo);
                    param.put("isCollectionGate", "Y");

                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");


                    String ss = httpUtils.postJson(String.valueOf(SPUtils.get(activity,"url","")) + BaseURL.URL_checkTicket, param);
                    final CheckTicketResponse response = new Gson().fromJson(ss, CheckTicketResponse.class);
//                    取消dialog
                    MyProgressUtils.dismissProgress();
                    int result = Integer.valueOf(response.getCode());

                    switch (result) {
                        case 0:

                            if (task == null) {

                                Intent intent = new Intent();
                                intent.putExtra("barCodeNo", response.getData().getBarcodeNo());
                                intent.putExtra("code", response.getCode());
                                intent.putExtra("message", response.getMessage());
                                intent.putExtra("sound", response.getData().getGateSoundName());

                                setResult(RESULT_OK, intent);
                                finish();

//                                Intent intent = new Intent();
//                                intent.putExtra("data", 666);
//                                setResult(RESULT_OK, intent);
//                                finish();
                            } else {
                                if (response.getData().getGateSoundName() != null) {
                                    she.lightGreen();

                                    PlayAudioFile(response.getData().getGateSoundName());
                                    ToastUtil.showToast("免费票：采集成功");
                                }
                            }

//                            ToastUtil.showToast("checkTicket_成功：" + response.getMessage());
                            break;

                        default:
                            she.lightRed();
                            PlayAudioFile(response.getMessage());
                            ToastUtil.showToast("checkTicket_失败：" + response.getMessage());
                            break;

                    }


                } catch (Exception e) {
                    ToastUtil.showToast("checkTicket异常：" + e.getMessage());
                }
            }
        }).start();
    }

//    void checkTicketAgain(final String checkType, final String typeData, final String gateNo) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//
//                // 先封装一个 JSON 对象
//                JSONObject param = new JSONObject();
//
//                try {
//
//                    param.put("searchDataType", checkType);
//                    param.put("searchData", typeData);
//                    param.put("checkCount", -1);
//                    param.put("gateNo", gateNo);
//                    param.put("isCollectionGate", "Y");
//
//                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
//                    param.put("timestamp", "20180611165000");
//
//
//                    String ss = httpUtils.postJson(BaseURL.URL_checkTicket, param);
//                    CheckTicketResponse response = new Gson().fromJson(ss, CheckTicketResponse.class);
//
//                    MyProgressUtils.dismissProgress();
//
//                    int result = Integer.valueOf(response.getCode());
//                    switch (result) {
//                        case 0:
//                            ToastUtil.showToast("checkTicket成功：" + response.getMessage());
//                            break;
////                        case 100009:
////                            if (checkType.equals(CheckType.TYPE_QRCODE)) {
////                                Message msg = new Message();
////                                msg.what = CheckType.handler_collect_qrCode;
////                                msg.obj = typeData;
////                                handler.sendMessage(msg);
////                            } else {
////                                Message msg = new Message();
////                                msg.what = CheckType.handler_collect_qrCode;
////                                msg.obj = typeData;
////                                handler.sendMessage(msg);
////                            }
////
////
////                            break;
////                        case 100010:
////
////                            break;
//                        default:
//                            ToastUtil.showToast("checkTicketAgain失败：" + response.getMessage());
//                            break;
//
//                    }
//
//
//                } catch (Exception e) {
//                    ToastUtil.showToast("checkTicket异常：" + e.getMessage());
//                }
//            }
//        }).start();
//    }

    void faceDataCollection(final String checkType, final String typeData, final String img_base64) {
        MyProgressUtils.showProgressDialog(activity);
        new Thread(new Runnable() {
            @Override
            public void run() {

                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {

                    param.put("imgType", checkType);
                    param.put("barcodeNo", typeData);
                    param.put("imgBaseData", img_base64);

                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");

                    String ss = httpUtils.postJson(String.valueOf(SPUtils.get(activity,"url","")) + BaseURL.URL_faceDataCollection, param);
                    FaceDataCollectionResponse response = new Gson().fromJson(ss, FaceDataCollectionResponse.class);
                    if (response.getCode().equals("0")) {


                        checkTicket(CheckType.TYPE_FACE, response.getData().getRowKey(), String.valueOf(SPUtils.get(activity,"CHECK_TICKET_TERMINAL_N0","")));

                    } else {
                        MyProgressUtils.dismissProgress();
                        ToastUtil.showToast(response.getMessage());
                    }

                } catch (Exception e) {
                    ToastUtil.showToast("faceDataCollection异常：" + e.getMessage());
                }
            }
        }).start();
    }


    void faceDataComparisonForOne(final String imgType, final String imgBaseData, final String imgUrl, final String barcodeNo, final String rowKey) {

        MyProgressUtils.showProgressDialog(activity);

        new Thread(new Runnable() {
            @Override
            public void run() {

                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {

                    param.put("imgType", imgType);
                    param.put("imgBaseData", imgBaseData);
                    param.put("imgUrl", imgUrl);
                    param.put("barcodeNo", barcodeNo);
                    param.put("rowKey", rowKey);

                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");


                    String ss = httpUtils.postJson(String.valueOf(SPUtils.get(activity,"url","")) + BaseURL.URL_faceDataComparisonForOne, param);
                    // TODO: 2019/7/30 response,再检票
                    FaceDataComparisonForOneResponse response2 = new Gson().fromJson(ss, FaceDataComparisonForOneResponse.class);
                    if (response2.getCode().equals("0")) {
                        double yz = 0.82;
                        if (response2.getData().getSimilarity() >= yz) {

                            checkTicket(CheckType.TYPE_FACE, rowKey, String.valueOf(SPUtils.get(activity,"CHECK_TICKET_TERMINAL_N0","")));

                        } else {

                            MyProgressUtils.dismissProgress();
                            she.lightRed();
                            PlayAudioFile("人脸比对失败");
                            Looper.prepare(); // No Looper is defined So define a new
                            new DialogUtils()
                                    .showCustomView2(activity,
                                            "比对结果",
                                            httpUtils.downloadBitmap(imgUrl),
//                                            BitmapFactory.decodeResource(getResources(), R.drawable.img_result_normal),

                                            BitmapFactory.decodeFile(filePath),
//                                            BitmapFactory.decodeResource(getResources(), R.drawable.img_result_success),

                                            new DialogUtils.ClickCallBack() {
                                                @Override
                                                public void ok() {

                                                }

                                                @Override
                                                public void cacel() {

                                                }
                                            });
                            Looper.loop();
                        }

                    } else {
                        MyProgressUtils.dismissProgress();
                        ToastUtil.showToast("faceDataComparisonForOne失败：" + response2.getMessage());
                    }


                } catch (Exception e) {
                    ToastUtil.showToast("faceDataComparisonForOne异常：" + e.getMessage());
                }
            }
        }).start();
    }


    void collectionFaceSaleTicket(final String imgTobase64String, final String humanCrednum, final String certificateTypeStr, final String humanName) {

        MyProgressUtils.showProgressDialog(activity);
        new Thread(new Runnable() {
            @Override
            public void run() {

                // 先封装一个 JSON 对象
                JSONObject param = new JSONObject();

                try {

//                    注释；
//                    之前的humanCrednum为类型
//                    certificateTypeStr为身份证；
//                    接口那边的是相反的，以接口为准
                    param.put("imgBaseData", imgTobase64String);
                    param.put("humanCrednum", certificateTypeStr);
                    param.put("certificateTypeStr", URLEncoder.encode(humanCrednum, "UTF-8"));
                    param.put("humanName", URLEncoder.encode(humanName, "UTF-8"));
                    param.put("userId", String.valueOf(SPUtils.get(activity,"USER_ID","")));
                    param.put("terminalId", String.valueOf(SPUtils.get(activity,"SALE_TICKET_TERMINAL_ID","")));

                    param.put("sign", "A96D48AE69F46BD0E1B17F10316086F3");
                    param.put("timestamp", "20180611165000");


                    String ss = httpUtils.postJson(String.valueOf(SPUtils.get(activity,"url","")) + BaseURL.URL_collectionFaceSaleTicket, param);
                    CollectionFaceSaleTicketResponse response = new Gson().fromJson(ss, CollectionFaceSaleTicketResponse.class);

                    MyProgressUtils.dismissProgress();

                    if (response.getCode().equals("0")) {

                        checkTicket(CheckType.TYPE_FACE, response.getData().getRowKey(), String.valueOf(SPUtils.get(activity,"CHECK_TICKET_TERMINAL_N0","")));

                    } else {

//                        这里要写到子线程吐司上面，放到吐司下面，语句不执行，就没法继续检票了
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (fmMask != null) {
                                    fmMask.setShoot();
                                }
                            }
                        });
                        MyProgressUtils.dismissProgress();
                        she.lightRed();
                        PlayAudioFile(response.getMessage());
                        ToastUtil.showToast("collectionFaceSaleTicket失败：" + response.getMessage());
                    }


                } catch (Exception e) {
                    ToastUtil.showToast("collectionFaceSaleTicket异常：" + e.getMessage());
                }
            }
        }).start();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        MyProgressUtils.dismissProgress();
    }
}
